package com.hmo.appshop;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.FocusHighlightHelper;
import androidx.leanback.widget.HorizontalGridView;
import androidx.leanback.widget.ItemBridgeAdapter;
import androidx.leanback.widget.OnChildViewHolderSelectedListener;
import androidx.recyclerview.widget.RecyclerView;

import com.hmo.http.BaseRequest;
import com.hmo.http.DownloadListener;

import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.hmo.appshop.MainActivity.spannable;

public class DetailsActivity extends FragmentActivity implements View.OnClickListener {

    public  static  ArrayList<Bitmap> bitmaps;
    public static PagerViewAdapter pagerViewAdapter;
    ProgressButton dInstall;
    String apk;
    Call call = null;

    @SuppressLint("RestrictedApi")
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction()==KeyEvent.ACTION_UP){
            int keyCode = event.getKeyCode();
            if (keyCode==KeyEvent.KEYCODE_BACK){
                //Log.d(TAG,"back");
//                CloseDialog closeDialog = new CloseDialog();
//                closeDialog.show(getSupportFragmentManager(),"closeDialog");
                if (call!=null)
                    call.cancel();
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        bitmaps=new ArrayList<>();

        AppBean appBean= null;
        Intent intent = getIntent();
        int id = intent.getIntExtra("id", 0);
        int type = intent.getIntExtra("type", 0);
        if (type==0){
            appBean=MainActivity.appBean0.get(id);
        }else if (type==1){
            appBean=MainActivity.appBean1.get(id);
        }else appBean=MainActivity.appBean2.get(id);

        apk = appBean.getApk();

        ImageView dLogo = findViewById(R.id.d_logo);

        dInstall = findViewById(R.id.d_install);
        TextView dTitle = findViewById(R.id.d_title);
        TextView dParam = findViewById(R.id.d_param);
        TextView dAbout = findViewById(R.id.d_about);

        dLogo.setImageBitmap(appBean.getLogo());
        dTitle.setText(appBean.getName());
        dParam.setText(appBean.getParam());
        dAbout.setText(spannable(appBean.getAbout()));
        dInstall.setOnClickListener(this);
        loadRow(appBean.getPicture());


    }

    private void loadRow(String[] picture) {
        HorizontalGridView dView = findViewById(R.id.d_view);

        final ArrayList<Bitmap> bitmaps = new ArrayList<>();
        //new BaseRequest().backBitmaps(picture,bitmaps);

        dView.setNumRows(1);
        dView.setDuplicateParentStateEnabled(true);
        dView.setOnChildViewHolderSelectedListener(new OnChildViewHolderSelectedListener() {
            @Override
            public void onChildViewHolderSelected(RecyclerView parent, RecyclerView.ViewHolder child, int position, int subposition) {
                super.onChildViewHolderSelected(parent, child, position, subposition);
            }

            @Override
            public void onChildViewHolderSelectedAndPositioned(RecyclerView parent, RecyclerView.ViewHolder child, int position, int subposition) {
                super.onChildViewHolderSelectedAndPositioned(parent, child, position, subposition);
            }
        });

        DetailPresenter detailPresenter = new DetailPresenter(getSupportFragmentManager(),bitmaps);

        pagerViewAdapter = new PagerViewAdapter(DetailsActivity.bitmaps);
        final ArrayObjectAdapter objectAdapter = new ArrayObjectAdapter(detailPresenter);

        new BaseRequest().backBitmaps(picture,objectAdapter);
        ItemBridgeAdapter itemBridgeAdapter = new ItemBridgeAdapter(objectAdapter);
        dView.setAdapter(itemBridgeAdapter);
        FocusHighlightHelper.setupHeaderItemFocusHighlight(itemBridgeAdapter);

    }


    @Override
    public void onClick(View view) {

        if (call!=null){
            Log.d("call", call.isExecuted()+"-"+call.isCanceled());
            if (!call.isCanceled()){
                return;
            }
        }


        String path = getBaseContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+File.separator+"appShop";
        File fPath = new File(path);
        if (!fPath.exists()){
            fPath.mkdirs();
        }

        final File file = new File(path,apk);
        if (!file.exists()) {
            dInstall.setText("连接中..");
            newCall(file);
        } else {
            try {
                ApkFile apkFile = new ApkFile(file);
                ApkMeta apkMeta = apkFile.getApkMeta();

                String packageName = apkMeta.getPackageName();
                Log.d("package", packageName);

                try {
                    ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo(packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES);
                    Log.d("name", applicationInfo.name);
                    Log.d("packageName", applicationInfo.packageName);
                    PackageManager packageManager = getPackageManager();

                    Intent intent = packageManager.getLaunchIntentForPackage(packageName);
                    startActivity(intent);
                } catch (PackageManager.NameNotFoundException e) {
                    installApk(file);
                }
            } catch (IOException e) {
                file.delete();
                newCall(file);
            }
        }
    }

    private void installApk(File apk){
        Intent intent = new Intent(Intent.ACTION_VIEW);

        Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), getApplication().getPackageName()+".fileprovider", apk);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        this.startActivityForResult(intent, 0);
    }

    private void newCall(final File file){
        call = new BaseRequest().download(apk, new DownloadListener() {
            @Override
            public void start(long max) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void loading(long progress) {
                dInstall.setProgress((int)progress);
                dInstall.setText(progress+"%");
//                    Message message = new Message();
//                    message.what= (int) progress;
//                    handler.sendMessage(message);
            }

            @Override
            public void complete(String path) {

            }

            @Override
            public void fail(int code, String message) {

            }

            @Override
            public void loadfail(String message) {

            }
        }, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("TAG", e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {

                    is = response.body().byteStream();

                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    installApk(file);

                } catch (Exception e) {
                    is.close();
                    fos.close();
                    fos.getFD().sync();
                    file.delete();
                    dInstall.setText("下载失败");
                }finally {

                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {

                    }
                    response.close();
                    call.cancel();
                }

            }
        });
    }

    //    private void initdata(String s) {
//        appBeans = new ArrayList<>();
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.abc);
//        ArrayList<Bitmap> bitmaps = new ArrayList<>();
//        bitmaps.add(bitmap);
//        bitmaps.add(bitmap);
//        bitmaps.add(bitmap);
//        bitmaps.add(bitmap);
//        bitmaps.add(bitmap);
//        bitmaps.add(bitmap);
//        bitmaps.add(bitmap);
//        String about="云视听极光是由广东南方新媒体发展有限公司与腾讯视频合作推出的一款针对客厅智能电视及机顶盒的互联网电视APP，可通过互联网电视应用市场下载，云视听极光融合了互联网极致、快速、迭代产品运营理念，为看官们提供更加丰富的优质视频内容。 [1]";
//        String param="大小：16.9MB | 版本号：6.0.0.1005 | 更新时间：20200921";
//        for (int i=0;i<10;i++){
//            AppBean appBean = new AppBean();
//            appBean.setId(i);
//            appBean.setName("软件"+i+s);
//            appBean.setPreView(bitmaps);
//            appBean.setAbout(MainActivity.spannable(about));
//            appBean.setParam(param);
//            Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
//            appBean.setLogo(bm);
//            appBeans.add(appBean);
//        }
//    }
}